import copy
from utils.conf import Response
from rest_framework.views import APIView
from ChatGPTServer.settings import formatResponseData, _request
import json


class ChatHome(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = []
    # 局部(本视图有效)权限类
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        ChatHome接口
        """
        data = copy.deepcopy(formatResponseData)
        try:
            question = request.data.get("question")

            # 异常拦截
            if not question:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            headers = {
                'accept': '*/*',
                'content-type': 'application/json',
                'origin': 'https://175.178.88.119',
                'referer': 'https://175.178.88.119/chat.html',
                'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
            }
            requestData = json.dumps({
                "model": "gpt-3.5-turbo",
                "messages": [
                    {
                        "role": "user",
                        "content": question
                    }
                ]
            })
            response = _request.post(url='https://175.178.88.119/chatgpt/chat', headers=headers, data=requestData)

            answer = response.json()["answer"]

            data["data"]["answer"] = answer
            return Response(data=data, loggerMsg=f"ChatHome接口响应成功：question={question}")

        except Exception as e:
            return Response(data=data, loggerMsg=f"ChatHome接口响应失败：{e}", isError=True)
